﻿using HslCommunication.Algorithms.PID;
using PopupWinTool.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VISAInstrument.Ports;

namespace PopupWinTool.Views
{
    /// <summary>
    /// 信号发生器SG1501B设置FM.xaml 的交互逻辑
    /// </summary>
    public partial class 信号发生器SG1501B设置FM : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// 属性通知
        /// </summary>
        /// <param name="properName"></param>
        private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _ComName = "";
        /// <summary>
        /// 端口名称
        /// </summary>
        public string ComName
        {
            get { return _ComName; }
            set { _ComName = value; RaisePropertyChanged(); }
        }

        private string _StationNumber = "";
        /// <summary>
        /// 工站
        /// </summary>
        public string StationNumber
        {
            get { return _StationNumber; }
            set { _StationNumber = value; RaisePropertyChanged(); }
        }

        private string _PinLv = "";
        /// <summary>
        /// 频率
        /// </summary>
        public string PinLv
        {
            get { return _PinLv; }
            set { _PinLv = value; RaisePropertyChanged(); }
        }

        private string _TiaoZhi = "";
        /// <summary>
        /// 调制
        /// </summary>
        public string TiaoZhi
        {
            get { return _TiaoZhi; }
            set { _TiaoZhi = value; RaisePropertyChanged(); }
        }

        private string _FuZhi = "";
        /// <summary>
        /// 幅值
        /// </summary>
        public string FuZhi
        {
            get { return _FuZhi; }
            set { _FuZhi = value; RaisePropertyChanged(); }
        }

        //外部传递进来的参数值
        public string 端口名称 { get; set; }
        public int 工站 { get; set; }
        public double 调制 { get; set; }
        public double 频率 { get; set; }
        public double 幅值 { get; set; }
        public string IP地址 { get; set; }
        public int IP端口号 { get; set; }
        public int Pass按钮值 { get; set; }
        public int Fail按钮值 { get; set; }
        public double 增量 { get; set; } = 5;
        public double 幅值下限 { get; set; } = 30;
        public double 幅值上限 { get; set; } = 100;

        /// <summary>
        /// 串口操作类
        /// </summary>
        private PortOperatorBase _portOperatorBase;
        /// <summary>
        /// 提示消息
        /// </summary>
        public string Message { get; private set; }
        /// <summary>
        /// 界面是否退出标志
        /// </summary>
        private bool _Exit = false;
        private IOHelper _IOHelper = new IOHelper();
        private int 幅值超限总数 = 0;


        /// <summary>
        /// 信号发生器SG1501B设置FM
        /// </summary>
        /// <param name="端口名称"></param>
        /// <param name="调制"></param>
        /// <param name="频率"></param>
        /// <param name="幅值"></param>
        public 信号发生器SG1501B设置FM()
        {
            InitializeComponent();
            DataContext = this;

            Task.Run(() =>
            {
                HslCommunication.Authorization.SetAuthorizationCode("f562cc4c-4772-4b32-bdcd-f3e122c534e3");  //dll授权
            });

            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(1000);
                var 打开结果 = _IOHelper.Open(IP地址, IP端口号);
                if (打开结果)
                {
                    Task.Run(检测是否按下Pass按钮线程);
                    Task.Run(检测是否按下Fail按钮线程);
                }
            });
        }
        /// <summary>
        /// 初始化数据
        /// </summary>
        public void Init()
        {
            //tbStationNumber.Text = 工站.ToString();
            //tbComName.Text = 端口名称;
            //tbTiaoZhi.Text = 调制.ToString();
            //tbPinLv.Text = 频率.ToString();
            //tbFuZhi.Text = 幅值.ToString();

            ComName = 端口名称;
            StationNumber = 工站.ToString();
            TiaoZhi = 调制.ToString();
            PinLv = 频率.ToString();
            FuZhi = 幅值.ToString();

            switch (工站)
            {
                case 1:
                    tb箭头1.Visibility = Visibility.Visible;
                    break;
                case 2:
                    tb箭头2.Visibility = Visibility.Visible;
                    break;
                default: break;
            }
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            _Exit = true;
            try
            {
                if (_IOHelper.IsOpen)
                    _IOHelper?.Close();
            }
            catch { }
        }
        /// <summary>
        /// 设置提示消息
        /// </summary>
        /// <param name="msg"></param>
        private void AppenText(string msg)
        {
            Dispatcher.Invoke(() =>
            {
                tbPrompt.Text = msg;
            });
        }
        /// <summary>
        /// 设置参数按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetFM_Click(object sender, RoutedEventArgs e)
        {
            AppenText("");
            try
            {
                //string comName = tbComName.Text;
                //string strTiaoZhi = tbTiaoZhi.Text;
                //string strPinlv = tbPinLv.Text;
                //string strFuZhi = tbFuZhi.Text;

                //if (string.IsNullOrWhiteSpace(comName))
                //{
                //    AppenText($"串口名称输入有误！！！");
                //    return;
                //}
                if (!double.TryParse(TiaoZhi, out double dTiaoZhi))
                {
                    AppenText($"调制输入有误！！！");
                    return;
                }
                if (!double.TryParse(PinLv, out double dPinLv))
                {
                    AppenText($"频率输入有误！！！");
                    return;
                }
                if (!double.TryParse(FuZhi, out double dFuZhi))
                {
                    AppenText($"幅值输入有误！！！");
                    return;
                }

                Message = string.Empty;
                调制 = dTiaoZhi;
                频率 = dPinLv;
                幅值 = dFuZhi;
                //执行设置信号发生器FM的方法
                bool 操作结果 = SetFM(ComName, dTiaoZhi, dPinLv, dFuZhi);
                if (!操作结果)
                {
                    AppenText($"设置参数失败，{Message}");
                    return;
                }

                //操作成功
                AppenText($"{DateTime.Now:HH:mm:ss.fff}  设置参数成功。。。");
            }
            catch (Exception ex)
            {
                AppenText($"设置参数异常，{ex.Message}");
                LogHelper.Error($"[信号发生器SG1501B设置FM.btnSetFM_Click]异常，{ex.Message}，{ex.StackTrace}");
            }
        }
        /// <summary>
        /// 设置FM
        /// </summary>
        /// <param name="comName"></param>
        /// <param name="dTiaoZhi"></param>
        /// <param name="dPinLv"></param>
        /// <param name="dFuZhi"></param>
        /// <returns></returns>
        private bool SetFM(string comName, double dTiaoZhi, double dPinLv, double dFuZhi)
        {
            Message = string.Empty;
            try
            {
                for (int i = 0; i < 2; i++)
                {
                    _portOperatorBase = new GpibPortOperator(comName);
                    _portOperatorBase.Open();
                    _portOperatorBase.Write($"FM {dTiaoZhi}KZ");
                    Thread.Sleep(5);
                    _portOperatorBase.Write($"FR {dPinLv} MZ");
                    Thread.Sleep(5);
                    _portOperatorBase.Write($"LE {dFuZhi} DU");
                    Thread.Sleep(5);
                    _portOperatorBase.Write("MR2");
                    Thread.Sleep(5);
                    _portOperatorBase.Write("FM ON");
                    Thread.Sleep(5);
                    _portOperatorBase.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                Message = $"异常，{ex.Message}";
                LogHelper.Error($"[信号发生器SG1501B设置FM.SetFM]异常，{ex.Message}，{ex.StackTrace}");
            }
            return false;
        }
        /// <summary>
        /// Pass按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPass_Click(object sender, RoutedEventArgs e)
        {
            if (_Exit)
            {
                return;
            }
            _Exit = true;
            Message = string.Empty;

            try
            {
                var win = this.Parent as Window;
                if (win != null)
                {
                    Message = "OK";
                    win.DialogResult = true;
                    win.Close();
                }
            }
            catch (Exception ex)
            {
                AppenText($"Pass异常，{ex.Message}");
                LogHelper.Error($"[信号发生器SG1501B设置FM.btnPass_Click]异常，{ex.Message}，{ex.StackTrace}");
            }
        }
        /// <summary>
        /// Fail按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFail_Click(object sender, RoutedEventArgs e)
        {
            //新需求，点击Fail，参数值 + 1，执行设置参数命令
            Message = string.Empty;
            btnAdd_Click(null, null);
            btnSetFM_Click(null, null);

            //增加判断幅值是否超出上限，连续两次超过上限，则关闭此界面，并且设置返回结果为NG，2024-10-10
            if (double.TryParse(FuZhi, out double dFuZhi))
            {
                if (dFuZhi > 幅值上限)
                {
                    _Exit = true;
                    _IOHelper?.Close();
                    Message = $"幅值超限，{dFuZhi}";
                    Dispatcher.Invoke(() =>
                    {
                        var win = this.Parent as Window;
                        if (win != null)
                        {
                            win.DialogResult = false;
                            win.Close();
                        }
                    });
                }
            }
            //if (double.TryParse(FuZhi, out double dFuZhi))
            //{
            //    if (dFuZhi > 幅值上限)
            //    {
            //        幅值超限总数 = 幅值超限总数 + 1;
            //    }
            //    else
            //    {
            //        幅值超限总数 = 0;
            //    }
            //    if (幅值超限总数 >= 2)
            //    {
            //        _Exit = true;
            //        _IOHelper?.Close();
            //        Message = "设置FM失败，幅值超限退出";
            //        Dispatcher.Invoke(() =>
            //        {
            //            var win = this.Parent as Window;
            //            if (win != null)
            //            {
            //                win.DialogResult = false;
            //                win.Close();
            //            }
            //        });
            //    }
            //}
        }
        /// <summary>
        /// 检测是否按下Pass按钮线程
        /// </summary>
        private void 检测是否按下Pass按钮线程()
        {
            while (!_Exit)
            {
                System.Threading.Thread.Sleep(10);
                if (_Exit)
                {
                    return;
                }

                var 操作结果 = _IOHelper.ReadDI(Pass按钮值, out bool 读取结果, out string 错误信息);
                if (!操作结果)
                {
                    continue;
                }

                if (读取结果)
                {
                    _Exit = true;
                    _IOHelper?.Close();
                    Dispatcher.Invoke(() =>
                    {
                        var win = this.Parent as Window;
                        if (win != null)
                        {
                            Message = "OK";
                            win.DialogResult = true;
                            win.Close();
                        }
                    });
                }
            }
        }
        /// <summary>
        /// 检测是否按下Fail按钮线程
        /// </summary>
        private void 检测是否按下Fail按钮线程()
        {
            while (!_Exit)
            {
                System.Threading.Thread.Sleep(10);
                if (_Exit)
                {
                    return;
                }

                var 操作结果 = _IOHelper.ReadDI(Fail按钮值, out bool 读取结果, out string 错误信息);
                if (!操作结果)
                {
                    continue;
                }

                //按下Fail按钮，幅值 + 1，并执行设置参数功能
                if (读取结果)
                {
                    btnFail_Click(null, null);
                }
            }
        }


        /// <summary>
        /// 增加按钮 - 幅值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!double.TryParse(FuZhi, out double dFuZhi))
                {
                    AppenText($"幅值有误！！！");
                    return;
                }

                dFuZhi = dFuZhi + 增量;
                FuZhi = dFuZhi.ToString();
            }
            catch (Exception ex)
            {
                AppenText($"异常，{ex.Message}");
                LogHelper.Error($"[信号发生器SG1501B设置FM.btnAdd_Click]异常，{ex.Message}，{ex.StackTrace}");
            }
        }
        /// <summary>
        /// 减少按钮 - 幅值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReduce_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!double.TryParse(FuZhi, out double dFuZhi))
                {
                    AppenText($"幅值有误！！！");
                    return;
                }

                dFuZhi = dFuZhi - 增量;
                FuZhi = dFuZhi.ToString();
            }
            catch (Exception ex)
            {
                AppenText($"异常，{ex.Message}");
                LogHelper.Error($"[信号发生器SG1501B设置FM.btnReduce_Click]异常，{ex.Message}，{ex.StackTrace}");
            }
        }
    }
}
